package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.exception.LogicException;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.stream.Collectors;

@Component
@Topic(TopicConfig.TASK_SUPPLY_TOPIC)
public class VMSupplyHandler implements MsgHandler {

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskService taskService;

    @Override
    public void process(String jsonMsg) throws IOException {
        //解析Json参数
        SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        if (supplyContract == null) {
            throw new LogicException("自动补货工单传参异常");
        }
        //找到工单执行人
        //取得设备信息
        VmVO vmInfo = vmService.getVMInfo(supplyContract.getInnerCode());
        //根据设备点位取得工单最少的人
        int userId = taskService.getLeastUser(vmInfo.getRegionId(), false);

        //封装工单信息
        TaskViewModel taskViewModel = new TaskViewModel();
        taskViewModel.setUserId(userId);
        taskViewModel.setDesc("自动补货工单");
        taskViewModel.setInnerCode(supplyContract.getInnerCode());
        taskViewModel.setCreateType(0);
        taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY);

        //封装补货信息
        taskViewModel.setDetails(supplyContract.getSupplyData().stream().map(sc -> {
            TaskDetailsViewModel taskDetailsViewModel = new TaskDetailsViewModel();
            taskDetailsViewModel.setChannelCode(sc.getChannelId());
            taskDetailsViewModel.setExpectCapacity(sc.getCapacity());
            taskDetailsViewModel.setSkuId(sc.getSkuId());
            taskDetailsViewModel.setSkuName(sc.getSkuName());
            taskDetailsViewModel.setSkuImage(sc.getSkuImage());

            return taskDetailsViewModel;
        }).collect(Collectors.toList())
        );
        //创建工单
        taskService.create(taskViewModel);
    }
}
